package com.aco.party.service.system;

import com.aco.party.dao.custom.CompanyDao;
import com.aco.party.dao.custom.UserDao;
import com.aco.party.enums.VisitTypeEnum;
import com.aco.party.model.po.Company;
import com.aco.party.model.po.User;
import com.aco.party.model.vo.CompanyParam;
import com.aco.party.model.vo.CompanyVo;
import com.aco.party.model.vo.VisitParam;
import com.aco.party.model.vo.common.PageParam;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by flying on 3/10/2016 0010.
 */
@Service
public class CompanyService {
    @Resource
    private CompanyDao companyDao;

    @Resource
    private UserDao userDao;

    @Resource
    private VisitService visitService;

    public List<CompanyVo> getByPage(PageParam pageParam,CompanyParam param) {
        List<CompanyVo> list = new ArrayList<>();
        List<Company> companys = companyDao.getList(pageParam,param);
        CompanyVo vo;
        if (companys != null) {
            for (Company company : companys) {
                vo = new CompanyVo();
                BeanUtils.copyProperties(company, vo);
                VisitParam visitParam = new VisitParam();
                visitParam.setType(VisitTypeEnum.公司.getValue());
                visitParam.setTargetId(vo.getId());
                vo.setViews(visitService.getCountByParam(visitParam).longValue());
                if(vo.getCreator() != null && vo.getCreator() != 0){
                    User user = userDao.selectByPrimaryKey(vo.getCreator());
                    if(user != null) {
                        vo.setCreatorStr(user.getNickName());
                    }
                }
                list.add(vo);
            }
        }
        return list;
    }

    public Integer getTotal(CompanyParam param) {
        return companyDao.getTotal(param);
    }

    public void update(Company company) {
        company.setUpdateTime(new Date());
        companyDao.updateByPrimaryKeySelective(company);
    }

    public void add(Company company) {
        company.setCreateTime(new Date());
        companyDao.insertSelective(company);
    }

    public void delete(Long id) {
        companyDao.deleteByPrimaryKey(id);
    }

    public Company getByPrimaryKey(Long id) {
        return companyDao.selectByPrimaryKey(id);
    }

    public CompanyVo getVoById(Long id) {
        CompanyVo vo = new CompanyVo();
        Company company = companyDao.selectByPrimaryKey(id);
        if(company != null)
            BeanUtils.copyProperties(company, vo);
        return vo;
    }
}
